<?php
/**
 * 71CMS [ 创先云智慧党建系统 ]
 * =========================================================
 * Copyright (c) 2018-2023 南宁小橙科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.71cms.net
 * 这不是一个自由软件！未经许可不能去掉71CMS相关版权。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 */
namespace app\api\controller;

use EasyWeChat\Factory;
use think\Db;

class Func extends Base
{
    public function initialize()
    {
        return parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function get_payment_list(){
//        $year = Db::name('payment') -> where(['uid'=>$this->user_id]) -> group('year') -> column('year');
//
//        rsort($year);
//
//        $list2 = [];
//        foreach($year as $k=>$v){
//            $list2[$k]['year'] = $v;
//            $list2[$k]['list'] = Db::name('payment') -> where(['year'=>$v,'uid'=>$this->user_id]) -> select();
//        }
//
        $data = input();
        $list2 = Db::name('payment') -> where(['year'=>$data['year'],'uid'=>$this->user_id]) -> select();

        jsonReturn(1,'成功获取',$list2);
    }

    public function pay(){
        $wx = Db::name('wxconfig')->find();

        $config = [
            'app_id' => $wx['app_id_app'],
            'mch_id' => $wx['mch_id_app'],
            'key' => $wx['key_app'],   // API 密钥
        ];
        if ($wx['is_sub'] == 1) {
            $config += ['sub_mch_id' => $wx['sub_mch_id_app']];
        }

        $app = Factory::payment($config);

        $payment = Db::name('payment')->where(['id' => input('id')])->find();
        if ($payment['end_time'] < date('Y-m-d')) {
            jsonReturn(0, '时间已截止');
        }

        $out_trade_no = date('YmdHis') . rand(100000, 999999);
        $unify = [
            'body' => "{$payment['name']}缴纳{$payment['title']}",
            'attach' => json_encode(['uid'=>$payment['uid'],'name'=>$payment['name']]),
//            'attach' => json_encode(['tenant_id' => TENANT_ID]),
            'out_trade_no' => $out_trade_no,
//            'total_fee' => $payment['payment'] * 100,
            'total_fee' => 1,
            'notify_url' => $wx['notify_url'],
//            'spbill_create_ip' => '222.84.235.117',
            'spbill_create_ip' => \EasyWeChat\Kernel\Support\get_client_ip(),
            'trade_type' => 'APP'
        ];

        $result = $app->order->unify($unify);

        $jssdk = $app->jssdk;

        $change_no = Db::name('payment') -> data(['out_trade_no'=>$out_trade_no]) -> where(['id'=>input('id')]) -> update();
        if(!$change_no){
            jsonReturn(0,'该单不存在');
        }

        if($result['result_code']=='FAIL'){
            jsonReturn(0,$result['err_code_des']);
        }


        $json = $jssdk->appConfig($result['prepay_id']);
        jsonReturn(1, 'app获取返回值', $json);
    }
}
